package com.logistics.controller;

import com.logistics.entity.Staff;
import com.logistics.service.StaffService;
import com.logistics.util.JsonUtil;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * Created by Ranger on 2015/8/18.
 */
@Controller
@RequestMapping("staff")
public class StaffController {
    @Resource
    StaffService staffService;

    /**
     * 添加职员信息
     * api     = /staff
     * method  = POST
     *
     * @param staff    需要添加的Staff对象
     * @param response HttpServletResponse的一个实例
     * @throws IOException 返回JSON数据给前端可能会抛出这个异常
     */
    @RequestMapping(method = RequestMethod.POST)
    public void addStaffRec(Staff staff, HttpServletResponse response) throws IOException {
        Integer staffId = staffService.add(staff);
        if (staffId != null) {
            JsonUtil.writeMsg(staffId.toString(), response);
        } else {
            JsonUtil.writeMsg("-1", response);
        }
    }

    /**
     * 删除职员信息
     * api    = /staff
     * method = DELETE
     *
     * @param idArray 要删除的职员记录的ID数组
     */
    @RequestMapping(method = RequestMethod.DELETE)
    public void deleteStaffRec(int[] idArray) {
        for (int id : idArray) {
            staffService.delete(id);
        }
    }

    /**
     * 获取职员信息
     * api     = /staff
     * method  = GET
     *
     * @param start    从第几条记录开始显示
     * @param size     页面显示的数据条数
     * @param response HttpServletResponse的一个实例
     * @throws IOException 返回JSON数据给前端可能会抛出这个异常
     */
    @RequestMapping(method = RequestMethod.GET)
    public void getJsonRecs(Integer start, Integer size, HttpServletResponse response) throws IOException {
        DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Staff.class);
        List<Staff> staffList = staffService.get(detachedCriteria, start, size);
        JsonUtil.write(staffList, response);
    }

    /**
     * 获取单个职员的信息
     * api     = /staff/staffId
     * method  = GET
     *
     * @param staffId  需要获取的职员的记录的ID
     * @param response HttpServletResponse的一个实例
     * @throws IOException 返回JSON数据给前端可能会抛出这个异常
     */
    @RequestMapping(value = "{staffId}", method = RequestMethod.GET)
    public void getJsonRec(@PathVariable("staffId") Integer staffId, HttpServletResponse response) throws IOException {
        JsonUtil.write(staffService.get(staffId), response);
    }

    /**
     * 修改职员记录
     * api      = /staff
     * method   = PUT
     *
     * @param staff 修改后的对象
     */
    @RequestMapping(value = "update", method = RequestMethod.PUT)
    public void updateStaff(Staff staff) {
        staffService.update(staff);
    }
}
